<template>
  <upload-excel :on-success="handleSuccess" />
</template>

<script>
import { reqEmployeeBatch } from '@/api/employee'
export default {
  name: 'Import',
  components: {},
  props: {},
  data() {
    return {}
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    // 处理上传成功的excel数据
    handleSuccess({ header, results }) {
    //   console.log(header, results)
    //   将results中数据批量的添加到服务器
    //   console.log(results)
      if (this.$route.query.type === 'employee') {
        this.handleEmployeeUpload(header, results)
      }

      // 批量上传工资
      // if(this.$route.query.type==='salary'){
      //     this.handleSalaryUpload()
      // }
    },

    async handleEmployeeUpload(header, results) {
    //   但需要的数据格式:[{username:xxx,mobile:xxx ....},{},{}]
    // ---------------------------------------
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      const resultArr = []
      results.forEach(item => {
        const obj = {}
        for (const k in item) {
          const enKey = userRelations[k]
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            obj[enKey] = this.formatExcelDate(item[k], '-')
          } else {
            obj[enKey] = item[k]
          }
        }
        resultArr.push(obj)
      })
      // ---以上代码是将数据的中文键转成英文键---
      //   console.log(resultArr)
      await reqEmployeeBatch(resultArr)
      this.$message.success('批量导入员工成功')
      this.$router.push('/employees')
    },
    // excel时间转换成js时间
    formatExcelDate(numb, format) {
      const time = new Date((numb) * 24 * 3600000 + 1) // 毫秒
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
      }
      //   format:"-"   =>  2022-03-17
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
      //   20220317
    }
  }
}
</script>

<style scoped lang=''>

</style>
